package com.itheima.app.controller;

import com.itheima.app.interceptor.UserHolder;
import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    UserManager userManager;



    //保存用户
    @PostMapping("/user/save")
    public Long save(@RequestBody User user){
        return userManager.save(user);
    }

    //根据手机查询用户
    @GetMapping("/user/findByMobile")
    public User findByMobile(String mobile){
        return userManager.findByMobile(mobile);
    }

    //发送验证码
    @PostMapping("/user/login")
    public void sendCode(@RequestBody Map<String,String> map){
        //获取手机号,调用manager完成发送验证码操作
        String phone = map.get("phone");

        //2.调用userManger中的方法实现操作
        userManager.sendCode(phone);
    }


    @PostMapping("/user/loginVerification")
    //注册登陆
    public ResponseEntity regAndLogin(@RequestBody Map<String,String> map){
        return userManager.regAndLogin(map);
    }


    // 完善用户基本信息
    @PostMapping("/user/loginReginfo")
    public ResponseEntity saveUserInfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token) {
        // 调用manager
        return userManager.saveUserInfo(userInfo, token);
    }


    // 补充用户信息头像
    @PostMapping({"/user/loginReginfo/head","/users/header"})
    public ResponseEntity saveUserInfoHead(MultipartFile headPhoto,@RequestHeader("Authorization") String token) throws IOException {
        return userManager.saveUserInfoHead(headPhoto,token);
    }


    //获取用户基本信息
    @GetMapping("/users")
    public ResponseEntity findUserInfoById(@RequestParam(required = false) Long userID,@RequestHeader("Authorization") String token){
        //1.判断userID有无值
        //2.有值,调用manager查询数据
        if (userID != null) {
            return userManager.findUserInfoById(userID);
        }else{
            //3.若无值,从token中获取用户信息,调用manager查询数据
            //User user = userManager.getUserFromToken(token);
            /*if (user == null) {
                return ResponseEntity.status(401).body(null);
            }*/
            User user = UserHolder.get();
            return userManager.findUserInfoById(user.getId());
        }
    }

    //更新用户信息
    @PutMapping("/users")
    public ResponseEntity updateUserInfo(@RequestBody UserInfo userInfo,@RequestHeader("Authorization") String token){
        return userManager.updateUserInfo(userInfo,token);
    }

}
